import React, {useCallback, useEffect, useRef, useState} from "react";

import {createForm} from 'rc-form';
import {
    NavBar, Icon, WhiteSpace, WingBlank, Pagination, SegmentedControl,
    Drawer, Popover, Modal, List, InputItem, TextareaItem, Stepper, ImagePicker,
    Button, Toast
} from "antd-mobile";
import {useHistory, useParams} from "react-router-dom";

import CopyFooter from "../../component/copyFooter";
import VerifyTagsInput from "../../component/verifyTagsInput";
import {ContentList} from "../../component/cardContent";
import {
    getBoxData,
    getBoxInBoxData,
    getObjectInBoxData,
    staticUrl,
    addObjectInBox,
    addBoxInBox,
    delBox
} from "../../requests";
import {getFormValidatorErrText} from '../../utils';


function DrawerContent({boxInfo}) {
    let rHistory = useHistory();

    return (
        <div className="drawer-content">
            <WhiteSpace/>
            <List style={{width: "100%"}} className={"box-info"} renderHeader={() => {
                return (
                    <p>盒子详情</p>
                )
            }} renderFooter={() => {
                return (
                    <p>创建时间：<span>{boxInfo.date}</span></p>
                )
            }}>
                <List.Item multipleLine={true} wrap={true}>
                    盒子名称：<List.Item.Brief/>
                    <span>{boxInfo.name}</span>
                </List.Item>
                <List.Item multipleLine={true} wrap={true}>
                    盒子描述：<List.Item.Brief/>
                    <span>{boxInfo.desc}</span>
                </List.Item>
                <List.Item multipleLine={true} wrap={true}>
                    盒子图片：<List.Item.Brief/>
                    <img style={{width: "100%", height: "auto"}} alt={"盒子图片"}
                         src={staticUrl(boxInfo.image)}/>
                </List.Item>
            </List>

            <WingBlank size={"lg"}>
                <Button type={"warning"} onClick={() => {
                    delBox({id: boxInfo.id}).then();
                    rHistory.replace("/boxlist");
                }}>删除盒子</Button>
            </WingBlank>
        </div>
    )
}

function AddButton(props) {
    let rParams = useParams();

    let {onAddObject, onAddBox} = props;
    let [openPopover, setOpenPopover] = useState(false);

    return (
        <Popover mask={true} visible={openPopover}
                 onVisibleChange={(visible) => setOpenPopover(visible)}
                 onSelect={({props}) => {
                     let {value} = props;
                     setOpenPopover(false);
                     if (value === "物品") {
                         onAddObject && onAddObject();
                     } else {
                         // 判断是否是api app环境
                         if (api) {

                             let FNScanner = api.require('FNScanner');
                             FNScanner.open({
                                 autorotation: true
                             }, function (ret, err) {
                                 if (ret.eventType === "success") {
                                     let box_id = ret.content;
                                     addBoxInBox({...rParams, box_id}).then(resp => {
                                         onAddBox && onAddBox();
                                     })
                                 }
                             });

                         }
                     }
                 }}
                 overlay={
                     [
                         (<Popover.Item key={"box"} value="盒子">加盒子</Popover.Item>),
                         (<Popover.Item key={"object"} value="物品">加物品</Popover.Item>),
                     ]
                 }>
            <img style={{width: 30, height: 30, marginRight: 16}}
                 src={require("../../media/images/tianjia.png")}
                 alt={"添加"}/>

        </Popover>
    )
}

const AddObjectFormModal = createForm()(function (props) {
    let rParams = useParams();

    let {visible, onClose, form, onReload} = props;
    let {getFieldProps, validateFields} = form;

    let [files, setFiles] = useState([]);
    let [disabledAddBtn, setDisabledAddBtn] = useState(false);

    return (
        <Modal visible={visible} closable={true} title={<h3>添加物品</h3>} className={"form-modal"}
               onClose={() => {
                   onClose && onClose();
               }}>
            <List>
                <InputItem {...getFieldProps("name", {rules: {required: true}})}
                           type={"text"} clear={true} placeholder={"请输入物品名称"}>物品名称</InputItem>
                <List.Item extra={
                    <Stepper {...getFieldProps("count", {initialValue: 1})}
                             style={{width: '100%', minWidth: '100px', touchAction: "none"}}
                             showNumber={true}
                             min={1}
                    />}>物品数量</List.Item>
                <List.Item>
                    物品关键字<VerifyTagsInput {...getFieldProps("keywords")}/>
                </List.Item>
                <TextareaItem {...getFieldProps("desc")}
                              title={"物品描述"} placeholder={"请输入物品描述"} count={200} rows={5} clear={true}/>
                <List.Item multipleLine={true}>
                    物品图片
                    <List.Item.Brief>选择一张图片</List.Item.Brief>
                    <ImagePicker className={"object-picker"} selectable={files.length < 1} length={2}
                                 files={files}
                                 onChange={(files, type, index) => {
                                     setFiles(files);
                                 }}/>
                </List.Item>
                <List.Item>
                    <Button type={"primary"} disabled={disabledAddBtn} loading={disabledAddBtn} onClick={() => {
                        validateFields(function (error, value) {
                            if (error) {
                                Toast.fail(getFormValidatorErrText(error));
                                return;
                            }

                            if (files.length < 1) {
                                Toast.fail("请给物品选择一张图片");
                                return;
                            }

                            setDisabledAddBtn(true);
                            value["keywords"] = value["keywords"] ? value["keywords"].join(",") : "";

                            addObjectInBox({...rParams, ...value, image: files[0].file}).then(function () {
                                onReload && onReload();
                                setDisabledAddBtn(false);
                            }).catch(err => {
                                Toast.fail("未知错误，创建失败");
                            });
                        });
                    }}>添加</Button>
                </List.Item>
                <List.Item>
                    <div style={{height: 300}}/>
                </List.Item>
            </List>
        </Modal>
    )
})

export default function BoxContent(props) {
    let rParams = useParams();
    let rHistory = useHistory();

    let [openDrawer, setOpenDrawer] = useState(false);
    let [objectModal, setObjectModal] = useState(false);

    let [boxInfo, setBoxInfo] = useState({});
    let [nowDataIndex, setNowDataIndex] = useState(0);
    let [data, setData] = useState([]);

    let [currentPage, setCurrentPage] = useState(0);
    let [total, setTotal] = useState(0);

    let reqData = useCallback(function (current) {
        Toast.loading("加载中...");
        current = current || currentPage;
        if (nowDataIndex === 0) {
            getObjectInBoxData({...rParams, page: current}).then(function (resp) {
                setData(resp.data.result);
                setTotal(resp.data.total);
                setCurrentPage(resp.data.current);
            }).finally(function () {
                Toast.hide();
            });
        } else {
            getBoxInBoxData({...rParams, page: current}).then(function (resp) {
                setData(resp.data.result);
                setTotal(resp.data.total);
                setCurrentPage(resp.data.current);
            }).finally(function () {
                Toast.hide();
            });
        }
    }, [nowDataIndex]);

    useEffect(function () {
        getBoxData(rParams).then(resp => {
            setBoxInfo(resp.data);
            setNowDataIndex(0);
        }).catch(e => {
            if (e.response.status === 404) {
                rHistory.replace("/createbox/" + rParams.id);
            }
        });
    }, [rParams]);

    useEffect(function () {
        reqData();
    }, [nowDataIndex]);


    return (
        <Drawer
            className="panel-drawer"
            style={{minHeight: document.documentElement.clientHeight}}
            sidebar={<DrawerContent boxInfo={boxInfo}/>}
            open={openDrawer}
            onOpenChange={() => {
                setOpenDrawer(false)
            }}
        >

            <NavBar
                mode="dark"
                icon={<Icon type="left"/>}
                onLeftClick={() => {
                    rHistory.replace("/");
                }}
                rightContent={[
                    <AddButton key="search"
                               onAddBox={() => {
                                   alert("添加成功");
                                   reqData(currentPage);
                               }}
                               onAddObject={() => setObjectModal(true)}/>,
                    <Icon key="ellipsis" type="ellipsis" onClick={() => setOpenDrawer(true)}/>,
                ]}
            >盒中内容</NavBar>
            <WhiteSpace/>

            <WingBlank>
                <SegmentedControl tintColor="#30A9DE" values={["物品", "盒子"]} selectedIndex={nowDataIndex}
                                  onChange={(e) => {
                                      setNowDataIndex(e.nativeEvent.selectedSegmentIndex);
                                  }}/>
                <WhiteSpace/>

                <ContentList data={data}/>
                <WhiteSpace/>

                {data.length > 0 ? (
                    <Pagination total={total} current={currentPage} onChange={(current) => {
                        reqData(current);
                    }}/>
                ) : ""}
            </WingBlank>

            <CopyFooter/>

            <AddObjectFormModal onClose={() => setObjectModal(false)} visible={objectModal}
                                onReload={() => {
                                    reqData(currentPage);
                                    setObjectModal(false);
                                }}/>
        </Drawer>
    );
}